package layouts;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.util.HashMap;

public class TileLayout implements LayoutManager2 {

	private HashMap<Component, Rectangle>	tileMap = new HashMap<Component, Rectangle>();
	
	private	int	numCols = 1;
	private int numRows = 1;
	
	
	@Override
	public void addLayoutComponent(String name, Component comp) {
		tileMap.put(comp, new Rectangle(1,1,1,1));
	}

	@Override
	public void removeLayoutComponent(Component comp) {
		tileMap.remove(comp);
	}

	@Override
	public Dimension preferredLayoutSize(Container parent) {
		return parent.getPreferredSize();
	}

	@Override
	public Dimension minimumLayoutSize(Container parent) {
		return parent.getMinimumSize();
	}

	@Override
	public void layoutContainer(Container parent) {
		// This is the method that will place the container
		Rectangle	view = parent.getBounds();
		int tx = view.width / getNumCols();
		int ty = view.height / getNumRows();
		
		for(Component comp : tileMap.keySet()) {
			Rectangle R = tileMap.get(comp);
			
			if (R!=null) {
				comp.setLocation(R.x * tx, R.y*ty);
				comp.setSize(R.width*tx, R.height*ty);
			}
		}
	}

	@Override
	public void addLayoutComponent(Component comp, Object constraints) {
		if (constraints==null || !(constraints instanceof Rectangle)) {
			constraints = new Rectangle(0,0,1,1);
		}
		tileMap.put(comp, (Rectangle) constraints);
	}

	@Override
	public Dimension maximumLayoutSize(Container target) {
		Rectangle R = tileMap.get(target);
		if (tileMap==null) {
			return new Dimension(0,0);
		} else {
			return new Dimension(R.width, R.height);
		}
	}

	@Override
	public float getLayoutAlignmentX(Container target) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public float getLayoutAlignmentY(Container target) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void invalidateLayout(Container target) {
		// TODO Auto-generated method stub
		
	}

	public int getNumCols() {
		return numCols;
	}

	public void setNumCols(int numCols) {
		this.numCols = Math.max(1, numCols);
	}

	public int getNumRows() {
		return numRows;
	}

	public void setNumRows(int numRows) {
		this.numRows = Math.max(1, numRows);
	}

}
